package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES 是一种可逆加密算法，对用户的敏感信息加密处理 对原始数据进行AES加密后，在进行Base64编码转化；
 */
@Slf4j
@Component
public class AECUtil {

    /**
     * AES加密
     *
     * @param sSrc
     * @param ivParameter
     * @param key
     * @return
     */
    public String encrypt(String sSrc, String ivParameter, String key) {
        String result = "";
        try {
            Cipher cipher;
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = key.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            result = new BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
            log.error("AES加密异常，原因：{}", e.getMessage(), e);
        }
        return result;
    }

    /**
     * AES解密
     *
     * @param sSrc
     * @param ivParameter
     * @param key
     * @return
     */
    public String decrypt(String sSrc, String ivParameter, String key) {
        try {
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            log.error("AES解密异常，原因：{}", ex.getMessage(), ex);
            return null;
        }
    }

    public static void main(String[] args) {
        String encryptStr = "rvKmun9lzazvKHv7RS5bVBpWZS2k71XdmDSXd5TolrpM6iiLakkd7Sy+mC0WMD61iYS0HOIM\\/KP9M6EqAU5AHjKf0AYid4i8GP73Sz7iYSp0XtPrAQ0sPwEc1rpVCfnoo2yJS2YddCOriKHhfAdqCGUjJGjYIVSEhdMKfW8\\/Qxpw+r0BDnwbGGo1cwkksx0k";
        encryptStr = java.net.URLDecoder.decode(encryptStr);
        System.out.println(encryptStr);
//        String result = new AECUtil().encrypt("1111", "35f5f88edb6445ae", "yXjYuXPnQMJSTXxmNtOiOEPNRgSThFwL");
        String result = new AECUtil().decrypt(encryptStr, "jwvpoFmqxAqRzgAE", "yXjYuXPnQMJSTXxmNtOiOEPNRgSThFwL");
        System.out.println(result);
    }
}
